package com.detrum.utils;

import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AlertDialog;

import com.detrum.base.R;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @MyOkHttpHelper 网络请求辅助类
 * 默认超时5秒
 */

public class MyOkHttpHelper {
    //初始化client,并设定连接超时--5秒
    static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
    MultipartBody.Builder multi_builder;
    MediaType MEDIATYPE_JSON = MediaType.parse("application/x-www-form-urlencoded");
    MediaType MEDIATYPE_UP = MediaType.parse("text/x-markdown");
    Request.Builder builder;
    private static MyOkHttpHelper utils;
    private Context context;

    private MyOkHttpHelper(Context context) {
        this.context = context;
    }

    public static MyOkHttpHelper getInstance(Context context) {
        if (utils == null) {
            utils = new MyOkHttpHelper(context);
        }
        return utils;
    }

    /**
     * 做GET请求
     *
     * @param url   不带参数的 请求地址
     * @param pairs 参数列表
     * @return
     */
    public MyOkHttpHelper doGet(String url, Map<String, String> pairs) {
        builder = new Request.Builder();
        if (pairs != null && pairs.size() != 0) {
            url = url + buildGetUrlOrder(pairs);
        }
        builder.url(url);
        return utils;
    }

    /**
     * 做put请求
     *
     * @param url 不带参数的 请求地址
     * @param map 参数集合
     * @return
     */
    public MyOkHttpHelper doPut(String url, Map<String, String> map) {
        builder = new Request.Builder();
        FormBody.Builder builder_f = new FormBody.Builder();
        RequestBody requestBody = null;
        if (map != null && map.size() != 0) {
            for (String key : map.keySet()) {
                if (map.get(key) == null) {
                    builder_f.add(key, "");
                } else {
                    builder_f.add(key, map.get(key));
                }
            }
            requestBody = builder_f.build();
        } else {
            requestBody = okhttp3.internal.Util.EMPTY_REQUEST;
        }
        builder.url(url).put(requestBody);
        return utils;
    }

    /**
     * 登录专用
     *
     * @param url
     * @param map 参数
     * @return
     */
    public MyOkHttpHelper doPostLogin(String url, Map<String, String> map) {
        builder = new Request.Builder();
        FormBody.Builder builder_f = new FormBody.Builder();
        for (String key : map.keySet()) {
            builder_f.add(key, map.get(key));
        }
        RequestBody requestBody = builder_f.build();
        builder.url(url).post(requestBody);
        return utils;
    }

    /**
     * 非登录全部带token和id
     *
     * @param url
     * @param map 参数
     * @return
     */
    public MyOkHttpHelper doPost(String url, Map<String, String> map) {
        builder = new Request.Builder();
        FormBody.Builder builder_f = new FormBody.Builder();
        if (map != null && map.size() != 0) {
            for (String key : map.keySet()) {
                if (map.get(key) == null) {
                    builder_f.add(key, "");
                } else {
                    builder_f.add(key, map.get(key));
                }
            }
        }

        RequestBody requestBody = builder_f.build();
        builder.url(url).post(requestBody);
        return utils;
    }

    /**
     * 注册发送验证码不带
     */
    public MyOkHttpHelper doPostSMS(String url, Map<String, String> map) {
        builder = new Request.Builder();
        FormBody.Builder builder_f = new FormBody.Builder();
        if (map != null && map.size() != 0) {
            for (String key : map.keySet()) {
                if (map.get(key) == null) {
                    builder_f.add(key, "");
                } else {
                    builder_f.add(key, map.get(key));
                }
            }
        }

        RequestBody requestBody = builder_f.build();
        builder.url(url).post(requestBody);
        return utils;
    }

    /**
     * 做用户登出 请求
     *
     * @param url 不带参数的url
     * @return
     */
    public MyOkHttpHelper doDetele(String url) {
        builder = new Request.Builder();
        builder.url(url).delete();
        return utils;
    }

    /**
     * 图片上传（通过File 形式 eg.<input type="file" name="nFime"/> ）
     *
     * @param url  接口地址
     * @param file 文件绝对地址（包含图片名称）
     * @return
     */
    public MyOkHttpHelper upLoadImage(String url, File file) {
        builder = new Request.Builder();
        LogUtils.i("Okhttp" + " Type==" + getMimeType(file.getName()));
        RequestBody requestBody1 = RequestBody.create(MediaType.parse(getMimeType(file.getName())), file);
        //分块请求构建RequestBody
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image", file.getName(), requestBody1).build();

        builder.url(url).post(requestBody).addHeader("enctype", "multipart/form-data");
        return utils;
    }

    Handler handler = new Handler();

    /**
     * 执行最后的请求操作
     *
     * @param back 回调（该操作已经在主线程里）
     */
    public void excute(int flag, final OKCallBack back) {
        if (MyMethod.isNetworkConnected(context)) {
            client.newCall(builder.build()).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (back != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                back.onFailure(R.string.web_fail);
                            }
                        });
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String result = response.body().string();

                    if (back != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!(result.equals(""))) {
                                    back.onResponse(result);
                                }
                            }
                        });

                    }
                }
            });
        } else {
            back.onInternetFail();
        }

    }

    public void excute_image(final OKCallBack2 back) {
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (back != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            back.onFailure("获取网络数据失败");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[] bytes = response.body().bytes();
                if (back != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!(bytes.equals(""))) {
                                back.onImage(bytes);
                            }
                        }
                    });

                }
            }
        });
    }

    private static String getMimeType(String filename) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(filename);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * get请求参数加工类
     *
     * @param pairs
     * @return
     */
    private String buildGetUrlOrder(Map<String, String> pairs) {
        if (pairs != null && !pairs.isEmpty()) {
            boolean isFirst = true;
            StringBuilder sb = new StringBuilder();
            for (String key : pairs.keySet()) {
                String value = pairs.get(key);
                if (isFirst) {
                    sb.append("?");
                    isFirst = false;
                } else {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }
            return sb.toString();
        }
        return "";
    }

    private String buildGetUrl(Map<String, String> pairs) {
        if (pairs != null && !pairs.isEmpty()) {
            boolean isFirst = true;
            StringBuilder sb = new StringBuilder();
            for (String key : pairs.keySet()) {
                String value = pairs.get(key);
                if (isFirst) {
                    sb.append("?");
                    isFirst = false;
                } else {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }
            return sb.toString();
        }
        return "";
    }

    public interface LoginOkCallBack {
        void onFailure(String message);

        void getToken(String token);

        void onResponse(String message);
    }

    public interface OKCallBack {
        void onFailure(int message);
        void onInternetFail();
        void onResponse(String message);
    }

    public interface OKCallBack2 {
        void onFailure(String message);

        void onResponse(String message);

        void onImage(byte[] bytes);
    }
}
